#include"../include/lib_headers.h"

char* update_file(char *file_path, char *data_file_path){
	long int length = 0;
	node *temp;
	FILE *fp;
	
	/* VFS not mounted */
	if (h == NULL || l1 == NULL) {
		sprintf(output_message,"%s %s","updatefile_FAILURE",ERR_VFS_UPDATEFILE_04);	
		return output_message;
	}
	
	/* Insufficient Arguments */
	if(strlen(file_path) == 0 || strlen(data_file_path) == 0){
		sprintf(output_message,"%s %s","updatefile_FAILURE",ERR_VFS_UPDATEFILE_00);	
		return output_message;
	}
	
	/* The file extension should be same */
/*	if(strcmp(file_extension(file_path),file_extension(data_file_path)) != 0){
		sprintf(output_message,"%s %s","updatefile_FAILURE",ERR_VFS_UPDATEFILE_02);	
		return output_message;		
	}
*/
	if(file_extension(file_path) == "txt" && (file_extension(data_file_path) != "h" || file_extension(data_file_path) != "txt" ) ){
		sprintf(output_message,"%s %s","updatefile_FAILURE",ERR_VFS_UPDATEFILE_02);	
		return output_message;		
	}
	/* Internal File not found */
	if(find_node(l1->next,file_path) == NULL || file_path[0] != '/'){
		sprintf(output_message,"%s %s","updatefile_FAILURE",ERR_VFS_UPDATEFILE_01);	
		return output_message;
	}
	else
		temp = find_node(l1->next, file_path);
	
	/* Only a file cn be updated */
	if(strcmp(find_node(l1->next, file_path)->fd_pointer->fileType, "dir") == 0){
		sprintf(output_message,"%s %s","updatefile_FAILURE",ERR_VFS_UPDATEFILE_01);	
		return output_message;
	}
		
	/* External file not found */	
	fp=fopen(data_file_path, "rb");
	if(fp==NULL){
		sprintf(output_message,"%s %s","updatefile_FAILURE",ERR_VFS_UPDATEFILE_02);	
		return output_message;
	}

	/*Storing the length of the file */
	fseek ( fp , 0 , SEEK_END ) ;
	length = ftell ( fp );

	/* File size is too large */
	if(ftell(fp) > (BLOCKSIZE)){
		sprintf(output_message,"%s %s","updatefile_FAILURE",ERR_VFS_UPDATEFILE_03);	
		return output_message;
	}
	rewind ( fp ) ;

	/* No file extension is there */
	if(strcmp(file_extension(data_file_path), "") == 0){
		sprintf(output_message,"%s %s","updatefile_FAILURE",ERR_VFS_UPDATEFILE_02);	
		return output_message;
	}
	
	temp -> fd_pointer -> fileSize = length ; 
	write_into_file(temp->fd_pointer->blockno, data_file_path);
	fclose(fp);
	sprintf(output_message,"%s","updatefile_SUCCESS");	
	return output_message;
}
